package service

import (
	"gf_ruoyi/internal/model"
	"net/http"

	"github.com/gogf/gf/v2/net/ghttp"
)

type (
	sMiddleware struct{}
)

var (
	insMiddleware = sMiddleware{}
)

//Middleware returns the interface of Middleware service
func Middleware() *sMiddleware {
	return &insMiddleware
}

//Ctx injects custom buiness context variable into context of current request
func (s *sMiddleware) Ctx(r *ghttp.Request) {
	customCtx := &model.Context{
		Session: r.Session,
	}
	Context().Init(r, customCtx)
	if user := Session().GetUser(r.Context()); user != nil {
		customCtx.User = &model.ContextUser{
			Id:       user.Id,
			Passport: user.Passwport,
			NickName: user.NicckName,
		}
	}
	r.Middleware.Next()
}

//Auth validates the request to allow only signed-in users visit
func (s *sMiddleware) Auth(r *ghttp.Request) {
	if User().IsSignedIn(r.Context()) {
		r.Middleware.Next()
	} else {
		r.Response.WriteStatus(http.StatusForbidden)
	}
}

//CORS allows Cross-origin resource sharing
func (s *sMiddleware) CORS(r *ghttp.Request) {
	r.Response.CORSDefault()
	r.Middleware.Next()
}
